/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrgs.jsopa;

/**
 * Our disc component has a semaphore to implement its dependency on a call from
 * the processor. The semaphore is private, and we offer a method "roda" that
 * unlocks it. Does it need to be synchronized??? It needs a semaphore to avoid
 * busy waiting...
 */
class Disco extends Thread {

    private IntController intCn;
    private Memory mem;
    private Semaphore sem;

    public Disco(IntController i, Memory m) {
        this.intCn = i;
        this.mem = m;
        this.sem = new Semaphore(0);
    }

    @Override
    public void run() {
        while (true) {
            // wait for some request comming from the processor
            sem.P();
            // Processor requested: now I have something to do...
            for (int i = 0; i < 4; ++i) {
                // sleep one disc turn here
                try {
                    sleep(Main.SLEEP_TIME);// was 50ms
                } catch (InterruptedException e) {
                }

                // if system went off while waiting, just shut down too
                if (!Main.isSystemOn()) {
                    Main.print("Disco shutting down");
                    return;
                }

                Main.print("disk made a turn");
            }
            // Here goes the code (2 lines) that generates an interrupt
            intCn.P();
            intCn.set(5);
        }
    }

    public void roda() {
        sem.V();
    }
}
